<!-- eslint-disable vue/require-default-prop -->
<template>
  <div style="position: relative; width: fit-content">
    <el-upload
      class="upload-comp"
      :class="{ hidden: uploadFilePojos.length >= trimedConfig.limit }"
      with-credentials
      v-bind="$attrs"
      :action="uploadURL"
      :multiple="trimedConfig.multiple"
      :before-upload="beforeUpload"
      :disabled="trimedConfig.disabled"
      :on-success="uploadSuccess"
      :on-error="uploadError"
      :file-list="fileList"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :limit="trimedConfig.limit"
      :data="mark"
      v-on="$listeners"
    >
      <div class="upload-slot flex-row-l">
        <span v-if="trimedConfig.uploadBtn" class="icon-container">
          <!-- <svg-icon icon-class="shangchuan" /> -->
          <span :style="{ 'font-size': fontSize }">{{
            trimedConfig.upBtnText
          }}</span>
        </span>
        <div
          style="margin-left: 4px; align-items: flex-start"
          :style="{ 'font-size': fontSize }"
          class="flex-col-l"
        >
          <div v-if="trimedConfig.sizeLimitTip" style="line-height: 20px">
            文件大小不能超过10M
          </div>
          <div
            v-if="trimedConfig.imgAndPdf"
            style="line-height: 20px; font-size: 10px"
          >
            支持pdf、png、jpg、jpeg格式
          </div>
        </div>
      </div>
    </el-upload>
    <template v-if="showPreview">
      <div
        v-if="fileList && fileList.length > 0"
        class="preview-btns flex-col"
        :class="{ hidden: uploadFilePojos.length >= trimedConfig.limit }"
      >
        <template v-for="item in fileList">
          <span
            v-if="item.url"
            :key="item.fileCode"
            style="margin-left: 10px; cursor: pointer; margin-top: -7px"
            @click="previewFiles(item.url)"
          >
            <el-tag>预览</el-tag>
          </span>
        </template>
      </div>
    </template>
  </div>
</template>

<script>
// import Pub from '@/services/pub.js'
export default {
  name: 'Upload',
  model: {
    prop: 'uploadFilePojos',
    event: 'upload'
  },
  props: {
    showPreview: {
      type: Boolean,
      default: true
    },
    // eslint-disable-next-line vue/require-default-prop
    fileType: Array,
    // eslint-disable-next-line vue/require-default-prop
    fontSize: {
      type: String
    },
    // eslint-disable-next-line vue/require-default-prop
    mark: {
      // 上传时携带的额外参数
      type: Object
    },
    // eslint-disable-next-line vue/require-default-prop
    onRemove: Function,
    // eslint-disable-next-line vue/require-default-prop
    uploadClass: String,
    uploadFilePojos: {
      type: Array,
      default() {
        return [];
      }
    },
    config: {
      type: Object,
      default(val) {
        return {
          disabled: false,
          multiple: false,
          limit: 1,
          imgAndPdf: false, // 是否图片与pdf
          img: false, // 是否图片
          sizeLimitTip: true, // 是否展示 文件大小限制10m 文案
          upBtnText: '点击上传'
        };
      }
    }
  },
  data() {
    return {
      uploadURL: 'www.baidu.com'
    };
  },
  computed: {
    trimedConfig() {
      const config = { ...(this.config || {}) };
      const keys = Object.keys(config);
      if (!keys.includes('disabled')) config.disabled = false;
      if (!keys.includes('multiple')) config.multiple = false;
      if (!keys.includes('limit')) config.limit = 1;
      if (!keys.includes('imgAndPdf')) config.imgAndPdf = false;
      if (!keys.includes('img')) config.img = false;
      if (!keys.includes('sizeLimitTip')) config.sizeLimitTip = true;
      if (!keys.includes('uploadBtn')) config.uploadBtn = true;
      if (!keys.includes('upBtnText')) config.upBtnText = '点击上传';
      return config;
    },
    fileList() {
      return this.uploadFilePojos.map((item) => {
        const result = {
          name: item.fileName,
          fileCode: item.fileCode,
          fileExtname: item.fileExtname,
          fileUrl: item.fileUrl
        };
        if (this.previewAble(item.fileExtname)) {
          const env = process.env.NODE_ENV;
          let url;
          if (env === 'production') {
            const path = `/files/${item.fileCode}.${item.fileExtname}`;
            const route = this.$router.resolve({ path });
            url = route.href;
          } else {
            url = `http://mgrdev.ldtamp.com/files/${item.fileCode}.${item.fileExtname}`;
          }
          result.url = url;
        }
        return result;
      });
    }
  },
  methods: {
    beforeUpload(file) {
      console.log(this.mark);
      const type = file.name.substring(file.name.lastIndexOf('.') + 1);
      const size = file.size;
      if (this.trimedConfig.imgAndPdf) {
        const reg = /(pdf|png|bmp|gif|jpe?g)/i;
        if (!reg.test(type)) {
          this.$message.error('只能上传pdf或图片！');
          return false;
        }
      }
      if (this.trimedConfig.img) {
        const reg = /(png|bmp|gif|jpe?g)/i;
        if (!reg.test(type)) {
          this.$message.error('只能上传图片！');
          return false;
        }
      }
      if (this.fileType) {
        if (!this.checkFileType(type)) {
          return false;
        }
      }
      if (!this.checkFileSize(size)) {
        return false;
      }
      return true;
    },
    checkFileSize(size) {
      const res = size < 10 * 1024 * 1024;
      if (!res) {
        this.$message.error('上传文件不能超过10M！');
        return false;
      }
      return true;
    },
    checkFileType(type) {
      if (this.fileType.includes(type)) {
        return true;
      } else {
        this.$message.error('上传文件格式不正确!');
        return false;
      }
    },
    uploadSuccess(response, file, fileList) {
      console.log(response, file, fileList);
      // eslint-disable-next-line no-prototype-builtins
      if (response.hasOwnProperty('resultCode') && +response.resultCode === 0) {
        const { fileCode, fileName, fileExtname, fileUrl } = response.data;
        // const fileExtname = fileName && (fileName + '').substring((fileName + '').lastIndexOf('.') + 1)
        const uploadFilePojos = this.uploadFilePojos;
        uploadFilePojos.push({
          fileCode,
          fileName,
          fileExtname,
          fileUrl
        });
        this.$emit('upload', uploadFilePojos);
        this.$emit('change', uploadFilePojos);
      }
    },
    handleRemove(file, fileList) {
      const uploadFilePojos = this.uploadFilePojos;
      const index = uploadFilePojos.findIndex(
        (item) => item.fileCode === file.fileCode
      );
      if (~index) {
        uploadFilePojos.splice(index, 1);
        this.$emit('upload', uploadFilePojos);
        this.$emit('change', uploadFilePojos);
        if (this.onRemove) {
          this.onRemove(file.fileCode);
        }
      }
    },
    uploadError(err, file, fileList) {
      let msg = '上传出错';
      if (err.message.indexOf('Maximum upload size exceeded')) {
        msg = '文件过大，请重新上传';
      }
      this.$message.error(msg);
    },
    previewAble(fileExtname) {
      const reg = /(jpe?g|png|gif|svg|bmp|pdf)/i;
      return reg.test(fileExtname);
    },
    handlePreview(file) {
      // const { fileCode } = file
      // Pub.downLoadFile({ fileCode }).then((res) => {
      //   this.$message.success('请求成功，开始下载')
      // })
    },
    // 预览
    previewFiles(url) {
      // window.open(`http://139.9.124.75:8012/onlinePreview?url=${url}`)
      window.open(url);
    }
  }
};
</script>

<style lang="scss" scoped>
.preview-btns {
  width: fit-content;
  position: absolute;
  z-index: 100;
  right: 0;
  top: 44px;
  transform: translate(100%);
  &.hidden {
    top: 0px;
  }
}
.upload-slot {
  .icon-container {
    margin-left: 4px;
    height: 25px;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    font-size: 12px;
    padding: 6px;
    box-sizing: border-box;
    display: inline-flex;
    justify-content: center;
    align-items: center;
  }
}
</style>

<style lang="scss">
.upload-comp {
  overflow: hidden;
  height: fit-content !important;
  &.hidden {
    .el-upload--text {
      display: none;
    }
    .el-upload--picture {
      display: none;
    }
  }
  .el-upload-list {
    position: relative;
    top: -4px;
    max-width: 222px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>
